package ren.steve.aspect;

import com.alibaba.fastjson.JSON;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;
import ren.steve.annotation.Log;
import ren.steve.common.utils.IpUtil;
import ren.steve.common.utils.JwtHelper;
import ren.steve.model.system.bean.SystemAccessLog;
import ren.steve.service.AsyncAccessLogService;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Collection;
import java.util.Map;

/**
 * @Author: CIS-T-13 Liu GuoJia
 * @Description:
 * @Date: Created in 2024/2/8 16:09
 */

@Aspect
@Component
public class LogAspect {

  // 服务切换为 feign 调用接口
  @Autowired
  private AsyncAccessLogService asyncAccessLogService;

  // 后置通知
  @AfterReturning(pointcut = "@annotation(controllerLog)", returning = "jsonResult")
  public void doAfterReturning(JoinPoint joinPoint, Log controllerLog, Object jsonResult) {
    handleLog(joinPoint, controllerLog, null, jsonResult);
  }

  protected void handleLog (final JoinPoint joinPoint, Log controllerLog, final Exception e, Object jsonResult) {
    try {
      RequestAttributes ra = RequestContextHolder.getRequestAttributes();
      ServletRequestAttributes sra = (ServletRequestAttributes) ra;
      HttpServletRequest request = sra.getRequest();

      // 数据库日志
      SystemAccessLog systemAccessLog = new SystemAccessLog();
      systemAccessLog.setStatus("000");
      // 请求地址
      String ip = IpUtil.getIpAddress(request);
      systemAccessLog.setAccessIp(ip);
      systemAccessLog.setAccessUrl(request.getRequestURI());
      String token = request.getHeader("token");
      String user = JwtHelper.getUserInfo(token,"code");
      systemAccessLog.setAccessName(user);

      if (e != null) {
        systemAccessLog.setStatus("001");
        systemAccessLog.setErrorMessage(e.getMessage());
      }
      String className = joinPoint.getTarget().getClass().getName();
      String methodName = joinPoint.getSignature().getName();
      systemAccessLog.setRequestMethod(request.getMethod());
      systemAccessLog.setMethod(className + "." + methodName + "()");

      getControllerMethodDescription(joinPoint, controllerLog, systemAccessLog, jsonResult);

      asyncAccessLogService.saveAccessLog(systemAccessLog);

    } catch (Exception exp) {
      // log.error("前置通知异常");
      // log.error("异常信息: {}", exp.getMessage());
      exp.printStackTrace();
    }

  }

  /**
   * 获取注解中对方法的描述信息 用于Controller层注解
   * @param log     日志
   * @param systemAccessLog 操作日志
   * @throws Exception
   */
  public void getControllerMethodDescription(JoinPoint joinPoint, Log log, SystemAccessLog systemAccessLog, Object jsonResult) throws Exception {
    // 设置action动作
    systemAccessLog.setBusinessType(log.businessType().name());
    // 设置标题
    systemAccessLog.setTitle(log.title());
    // 设置操作人类别
    systemAccessLog.setAccessType(log.operatorType().name());
    // 是否需要保存request，参数和值
    if (log.isSaveRequestData()) {
      // 获取参数的信息，传入到数据库中。
      setRequestValue(joinPoint, systemAccessLog);
    }
    // TODO: 是否需要保存response，参数和值
    if (log.isSaveResponseData() && !StringUtils.isEmpty(jsonResult)) {
      // systemAccessLog.setResultParams(JSON.toJSONString(jsonResult));
    }
  }

  /**
   * 获取请求的参数，放到log中
   * @param systemAccessLog 操作日志
   * @throws Exception 异常
   */
  private void setRequestValue(JoinPoint joinPoint, SystemAccessLog systemAccessLog) throws Exception {
    String requestMethod = systemAccessLog.getRequestMethod();
    try {
      // 保存所有 请求 和 响应参数
      // if (HttpMethod.PUT.name().equals(requestMethod) || HttpMethod.POST.name().equals(requestMethod)) {
      String params = argsArrayToString(joinPoint.getArgs());
      systemAccessLog.setAccessParams(params);
      // }
    } catch (Exception e) {
      // 参数错误异常处理
      systemAccessLog.setErrorMessage(e.toString());
    }
  }

  /**
   * 参数拼装
   */
  private String argsArrayToString(Object[] paramsArray) {
    String params = "";
    if (paramsArray != null) {
      for (Object o : paramsArray) {
        if (!StringUtils.isEmpty(o) && !isFilterObject(o)) {
          try {
            Object jsonObj = JSON.toJSON(o);
            params += jsonObj.toString() + " ";
          } catch (Exception e) {
          }
        }
      }
    }
    return params.trim();
  }

  /**
   * 判断是否需要过滤的对象。
   * @param o 对象信息。
   * @return 如果是需要过滤的对象，则返回true；否则返回false。
   */
  @SuppressWarnings("rawtypes")
  public boolean isFilterObject(final Object o) {
    Class<?> clazz = o.getClass();
    if (clazz.isArray()) {
      return clazz.getComponentType().isAssignableFrom(MultipartFile.class);
    } else if (Collection.class.isAssignableFrom(clazz)) {
      Collection collection = (Collection) o;
      for (Object value : collection) {
        return value instanceof MultipartFile;
      }
    } else if (Map.class.isAssignableFrom(clazz)) {
      Map map = (Map) o;
      for (Object value : map.entrySet()) {
        Map.Entry entry = (Map.Entry) value;
        return entry.getValue() instanceof MultipartFile;
      }
    }
    return o instanceof MultipartFile || o instanceof HttpServletRequest || o instanceof HttpServletResponse
      || o instanceof BindingResult;
  }

}
